package cn.com.dingtek.genius.manager.server.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class CookieUtil {
    public static void putCookie(String name, String value, int maxAge, HttpServletRequest request, HttpServletResponse response) {
        putCookie(null, name, value, maxAge, false, request, response);
    }

    public static void putCookie(String domain, String name, String value, int maxAge, boolean httpOnly, HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie(name, value);

        if (maxAge >= 0) {
            cookie.setMaxAge(maxAge);
        }

        cookie.setPath(getCookiePath(request));

        if (domain != null) {
            cookie.setDomain(domain);
        }

        if (maxAge < 1) {
            cookie.setVersion(1);
        }

        cookie.setSecure(request.isSecure());
        cookie.setHttpOnly(httpOnly);
        response.addCookie(cookie);
    }

    private static String getCookiePath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        return contextPath.length() > 0 ? contextPath : "/";
    }

    public static String extractCookie(String name, HttpServletRequest request) {
        Objects.requireNonNull(name);

        Cookie[] cookies = request.getCookies();

        if ((cookies == null) || (cookies.length == 0)) {
            return null;
        }

        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }

        return null;
    }

    public static void cancelCookie(String name, HttpServletRequest request, HttpServletResponse response) {
        cancelCookie(null, name, request, response);
    }

    public static void cancelCookie(String domain, String name, HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie(name, null);
        cookie.setMaxAge(0);
        cookie.setPath(getCookiePath(request));
        if (domain != null) {
            cookie.setDomain(domain);
        }
        response.addCookie(cookie);
    }
}
